class_name aiDecision extends Node

enum ACTIONS {
	GET_GEM,
	SAVE_CARD,
	BUY_CARD
}

static func make_decision():
	var best_action = evaluate_action()
	return best_action

static func evaluate_action():
	var all_possible_actions = [ACTIONS.GET_GEM,ACTIONS.SAVE_CARD,ACTIONS.BUY_CARD] #0-拿宝石 1-预留卡 2-购买卡
	var possible_actions = []
	var score = 0
	
	#评估购买卡
	var purchasable_cards = get_purchasable_cards()
	if purchasable_cards.size() > 0:
		var best_card = select_best_card(purchasable_cards)
		possible_actions.append({
			"type": "purchase",
			"card": best_card,
			"score": calculate_card_score(best_card)
		})
	
	 # 评估预留卡牌动作
	var reservable_cards = get_reservable_cards()
	if reservable_cards.size() > 0:
		var best_reserve = select_best_reserve(reservable_cards)
		possible_actions.append({
			"type": "reserve",
			"card": best_reserve,
			"score": calculate_reserve_score()
		})
	
	# 评估拿取宝石动作
	var gem_options = GameManager.available_gems
	if gem_options.size() > 0:
		var best_gem = select_best_gem(gem_options)
		possible_actions.append({
			"type": "take_gems",
			"gems": best_gem,
			"score": calculate_gem_score()
		})
	
	# 选择最高分动作
	possible_actions.sort_custom(func(a, b): return a["score"] > b["score"])
	return possible_actions[0]


# 获取可购买卡牌（包含已预留的）
static func get_purchasable_cards() -> Array:
	var purchasable = []
	# 检查场上卡牌
	for card in GameManager.card_on_deck_node.get_children():
		if can_afford(card.card_info):
				purchasable.append(card.card_info)
	# 检查已预留卡牌
	for card in GameManager.players[1].reserved_cards:
		if can_afford(card):
			purchasable.append(card)
	return purchasable

# 判断是否能支付卡牌费用
static func can_afford(card) -> bool:
	return ruleSystem.can_purchase_card(GameManager.players[1],card)

static func select_best_card(arr:Array):
	# 当前返回随机一项，可增加AI决策逻辑
	var tempArr:Array = arr
	tempArr.shuffle()
	return tempArr.pop_back()
	
static func select_best_reserve(arr:Array):
	# 当前返回随机一项，可增加AI决策逻辑
	var tempArr:Array = arr
	tempArr.shuffle()
	return tempArr.pop_back()
	
static func calculate_card_score(best_card):
	return 10
	
static func get_reservable_cards():
	return GameManager.players[1].reserved_cards
	
static func calculate_reserve_score():
	return 9
	
static func calculate_gem_score():
	return 8
	
static func select_best_gem(gems):
	
	var temp = []
	for idx in range(5):
		if GameManager.available_gems[idx] > 0:
			temp.append(idx)
	temp.shuffle()
	var re = {
		Globals.COIN_COLOR.WHITE:0,
		Globals.COIN_COLOR.BLUE:0,
		Globals.COIN_COLOR.RED:0,
		Globals.COIN_COLOR.GREEN:0,
		Globals.COIN_COLOR.BROWN:0,
	}
	if temp.size() > 0:
		re[temp.pop_back()] += 1
	if temp.size() > 0:
		re[temp.pop_back()] += 1
	if temp.size() > 0:
		re[temp.pop_back()] += 1
	return [re[0],re[1],re[2],re[3],re[4],0]
	
